package com.liveinstars.im.core;

import io.netty.channel.Channel;
import lombok.Data;
import lombok.ToString;

import java.util.Objects;

@Data
@ToString
public class Session {
	public enum SessionType {
		/**
		 * 服务器到客户端的session
		 */
		SC,
		/**
		 * 服务器之间的session
		 */
		SS
	}

	private Channel channel;

	private String clientId;

	private SessionType type;

	private String serverIpPort;

	/**
	 * 用户id
	 */
	private Long userId;

	/**
	 * 生成服务端对服务端的session
	 * 
	 * @param channel
	 */
	public Session(Channel channel, String serverIpPort) {
		this.channel = channel;
		this.type = SessionType.SS;
		this.serverIpPort = serverIpPort;
	}

	/**
	 * 生成服务端对客户端session
	 *
	 * @param clientId
	 * @param channel
	 * @param userId
	 */
	public Session(String clientId, Channel channel, Long userId) {
		this.channel = channel;
		this.type = SessionType.SC;
		this.userId = userId;
		this.clientId = clientId;
	}

	/**
	 * 发送消息
	 * 
	 * @param msg
	 */
	public void send(Object msg) {
		// 如果是语音消息则附带上语音
		channel.writeAndFlush(msg);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o){
			return true;
		}
		if (!(o instanceof Session)){
			return false;
		}

		Session session = (Session) o;
		return getUserId().equals(session.getUserId())  &&
				Objects.equals(getChannel(), session.getChannel()) &&
				getType() == session.getType() &&
				Objects.equals(getServerIpPort(), session.getServerIpPort()) &&
				Objects.equals(getClientId(), session.getClientId());
	}

	@Override
	public int hashCode() {
		return Objects.hash(getClientId(), getChannel(), getType(), getUserId());
	}
}
